import { defineStore } from "pinia";
import $ from "@axios/request";
import { ElMessageBox, ElMessage } from "element-plus";
import { useRouter } from "vue-router";
const mainStore = defineStore("main", {});
const _G = mainStore();
const supplierpro = defineStore("supplierpro", {
  state: () => ({
    //  _g: glob(),
    router: useRouter(),
    activeName: "first",
    P_Form: {},
    P_Table: [],
    P_PagingConfig: {},
    P_Params: {
      pageNumber: 1,
      pageSize: 20,
    },
    P_GetUserAll: [],
  }),
  actions: {
    // 保存/修改 供应商基础信息
    async Hp_Save() {
      let type = "Put";
      if (this.P_Form.supplierId) {
        type = "Post";
      }
      const responsibleUser = [this.P_Form.responsibleUser];
      await $[type]({
        data: {
          ...this.P_Form,
          responsibleUser,
        },
        url: "/supplier",
      }).then((res) => {
        if (type == "Put") {
          this.router.push("/supplierpro/home");
          ElMessage.success("新增成功");
        } else {
          this.Hp_GetIdSee(_G.M.GetId());
          ElMessage.success("修改成功");
        }
      });
    },
    // 查询所有工程师
    async Hp_GetUserAll() {
      await $.Get({
        url: "/supplier/findResponsibleUser",
      }).then((res) => {
        this.P_GetUserAll = res.data;
      });
    },

    async Hp_GetSearch() {
      await $.Get({
        url: "/supplier/page",
        data: this.P_Params,
      }).then((res) => {
        console.log(res.data);
        this.P_Table = res.data.records;
        this.P_PagingConfig = {
          total: res.data.total,
          pageSize: res.data.size,
          pageNumber: res.data.current,
        };
      });
    },

    async Hp_GetIdSee(id) {
      await $.Get({
        url: "/supplier/" + id,
      }).then((res) => {
        const { responsibleUser } = res.data;
        res.data.responsibleUser = responsibleUser[0];
        this.P_Form = res.data;
      });
    },

    async Hp_Del(id) {
      const url = "/supplier/" + id;
      await $.Del(url).then((res) => {
        ElMessage.success("删除成功");
        this.Hp_GetSearch();
      });
    },

    //文件上传
    async Hp_Upload(data) {
      return await $.Up(data.raw);
    },

    // 下载
    async Hp_Download(id) {
      return await $.Dow(id);
    },
    // 质量协议
    async Hp_SevaQuality(data) {
      try {
        const { files, ...rest } = data;
        let agreementFile = [];

        // 处理文件上传
        if (files && files.length) {
          const uploadPromises = files.map((file) => this.Hp_Upload(file));
          const results = await Promise.all(uploadPromises);
          agreementFile = results.map((res) => res.id);
        }

        // 判断请求类型
        const type = data.qualityAgreementId ? "Post" : "Put";

        // 批量保存协议
        if (agreementFile.length) {
          const savePromises = agreementFile.map((fileId) =>
            $[type]({
              url: "/supplier/qualityAgreement",
              data: { ...rest, agreementFile: fileId },
            })
          );
          await Promise.all(savePromises);
        } else {
          await $[type]({
            url: "/supplier/qualityAgreement",
            data: { ...rest, agreementFile: null },
          });
        }

        ElMessage.success("保存成功");
        // 刷新列表
        await this.Hp_GetIdSee(_G.M.GetId());
      } catch (error) {
        ElMessage.error("保存失败");
        console.error(error);
      }
    },

    async Hp_DelQuality(id) {
      const url = "/supplier/qualityAgreement/" + id;
      $.Del(url).then((res) => {
        ElMessage.success("删除成功");
        this.Hp_GetIdSee(_G.M.GetId());
      });
    },

    // ROSH 协议
    async Hp_SevaRosh(data) {
      try {
        const { files, ...rest } = data;
        let agreementFile = [];
        // 判断请求类型
        const type = data.roshAgreementId ? "Post" : "Put";

        // 处理文件上传
        if (files && files.length) {
          const uploadPromises = files.map((file) => this.Hp_Upload(file));
          const results = await Promise.all(uploadPromises);
          agreementFile = results.map((res) => res.id);
        }

        // 批量保存协议
        if (agreementFile.length) {
          const savePromises = agreementFile.map((fileId) =>
            $[type]({
              url: "/supplier/roshAgreement",
              data: { ...rest, agreementFile: fileId },
            })
          );
          await Promise.all(savePromises);
        } else {
          await $[type]({
            url: "/supplier/roshAgreement",
            data: { ...rest, agreementFile: null },
          });
        }

        ElMessage.success("保存成功");
        // 刷新列表
        await this.Hp_GetIdSee(_G.M.GetId());
      } catch (error) {
        ElMessage.error("保存失败");
        console.error(error);
      }
    },

    async Hp_DelRosh(id) {
      const url = "/supplier/roshAgreement/" + id;
      $.Del(url).then((res) => {
        ElMessage.success("删除成功");
        this.Hp_GetIdSee(_G.M.GetId());
      });
    },

    // 质量目标
    async Hp_SevaQualityObjectives(data) {
      console.log(data);

      // return;
      try {
        const { files, ...rest } = data;
        // 判断请求类型
        const type = data.qualityObjectivesId ? "Post" : "Put";
        let agreementFile = [];
        // 处理文件上传
        if (files && files.length) {
          const uploadPromises = files.map((file) => this.Hp_Upload(file));
          const results = await Promise.all(uploadPromises);
          agreementFile = results.map((res) => res.id);
        }

        // 批量保存协议
        if (agreementFile.length) {
          const savePromises = agreementFile.map((fileId) =>
            $[type]({
              url: "/supplier/qualityObjectives",
              data: { ...rest, qualityObjectivesFile: fileId },
            })
          );
          await Promise.all(savePromises);
        } else {
          $[type]({
            url: "/supplier/qualityObjectives",
            data: {
              ...rest,
              qualityObjectivesFile: agreementFile ? agreementFile[0] : null,
            },
          });
        }

        ElMessage.success("保存成功");
        // 刷新列表
        await this.Hp_GetIdSee(_G.M.GetId());
      } catch (error) {
        ElMessage.error("保存失败");
        console.error(error);
      }
    },

    async Hp_DelQualityObjectives(id) {
      const url = "/supplier/qualityObjectives/" + id;
      $.Del(url).then((res) => {
        ElMessage.success("删除成功");
        this.Hp_GetIdSee(_G.M.GetId());
      });
    },

    // 审核计划
    async Hp_SevaAuditPlan(data) {
      try {
        const { files, examineId, ...rest } = data;
        let agreementFile = [];

        // 处理文件上传
        if (files && files.length) {
          const uploadPromises = files.map((file) => this.Hp_Upload(file));
          const results = await Promise.all(uploadPromises);
          agreementFile = results.map((res) => res.id);
        }

        if (examineId) {
          delete rest.annex;
          delete rest.annexFiles;
          delete rest.updateTime;
          delete rest.createTime;
          delete rest.status;
          delete rest.useFlag;
        }

        // 判断请求类型
        const type = data.examineId ? "Post" : "Put";
        $[type]({
          url: "/supplier/examine",
          data: {
            ...rest,
            examineId,
            annex: agreementFile.length ? agreementFile : null,
          },
        }).then((e) => {
          this.Hp_GetIdSee(_G.M.GetId());
        });
      } catch (error) {
        ElMessage.error("保存失败");
        console.error(error);
      }
    },
    async Hp_GetAuditPlan(id) {
      $.Get({
        url: "/supplier/examine/" + id,
      }).then((res) => {
        this.P_Form = res.data;
      });
    },

    async Hp_DelAuditPlan(id) {
      const url = "/supplier/examine/" + id;
      $.Del(url).then((res) => {
        ElMessage.success("删除成功");
        this.Hp_GetIdSee(_G.M.GetId());
      });
    },

    // 问题相关
    async Hp_SevaAuditIssues(data, type) {
      try {
        const { files, ...rest } = data;
        let agreementFile = [];

        // 处理文件上传
        if (files && files.length) {
          const uploadPromises = files.map((file) => this.Hp_Upload(file));
          const results = await Promise.all(uploadPromises);
          agreementFile = results.map((res) => res.id);
        }

        // 判断请求类型
        const type = data.auditIssuesId ? "Post" : "Put";

        $[type]({
          url: "/supplier/auditIssues",
          data: { ...rest, annex: agreementFile.length ? agreementFile : null },
        }).then((res) => {
          ElMessage.success("保存成功");
        
            // 刷新列表
            this.Hp_GetIdSee(_G.M.GetId());
          
        });
      } catch (error) {
        ElMessage.error("保存失败");
        console.error(error);
      }
    },
    async Hp_GetAuditIssues(id) {
      $.Get({
        url: "/supplier/auditIssues/" + id,
      }).then((res) => {
        this.P_Form = res.data;
      });
    },

    async Hp_DelAuditIssues(id) {
      const url = "/supplier/auditIssues/" + id;
      $.Del(url).then((res) => {
        ElMessage.success("删除成功");
        this.Hp_GetIdSee(_G.M.GetId());
      });
    },

    // 审核
    async Hp_ExamineQuality(type, id) {
      const url = `/supplier/${type}/approval/${id}`;
      $.Post({
        url,
      }).then((res) => {
        ElMessage.success("审核成功");
        this.Hp_GetIdSee(_G.M.GetId());
      });
    },
    //获取所有供应商
    async Hp_GetEquipmentAll() {
      await $.Get({
        url: "/supplier/findAllIdAndName",
      }).then((res) => {
        this.P_findAllIdAndName = res.data;
      });
    },


    // 新 审核计划
    async Hp_SevaAuditPlanNew(data) {
      await $.Put({
        url: "/supplier/examine",
        data,
      }).then((res) => {
        ElMessage.success("保存成功");
        this.Hp_GetIdSee(_G.M.GetId());
      });
    },

    // 补充审核计划
    async Hp_SevaAuditPlanSupplement(data) {
      const { files,annex,reportFiles,report,...rest } = data;
      const list = [];
      if (files && files.length) {
        const uploadPromises = files.map((file) => this.Hp_Upload(file));
        const results = await Promise.all(uploadPromises);
        results.map((res) => list.push(res.id));
      }

      const annexList = annex || [];  // 如果 annex 为空则使用空数组

      const reportlist = [];
      if(reportFiles && reportFiles.length){
        const uploadPromises = reportFiles.map((file) => this.Hp_Upload(file));
        const results = await Promise.all(uploadPromises);
        results.map((res) => reportlist.push(res.id));
      }
      const reportidlist = report || [];  // 如果 report 为空则使用空数组

      await $.Post({
        url: "/supplier/examine",
        data:{annex:[...annexList,...list],report:[...reportlist,...reportidlist],...rest},
      }).then((res) => {
        ElMessage.success("保存成功");
        this.Hp_GetIdSee(_G.M.GetId());
      });
    },

    // 审核计划
    async Hp_GetAuditPlanNew(id) {
      await $.Post({
        url:'/supplier/examine/approval/'+id,
      }).then((res)=>{
        ElMessage.success('审核成功');
        this.Hp_GetIdSee(_G.M.GetId());
      })
    }
  },
});

export default supplierpro;
